package com.szyjjk.util;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLDecoder;
import java.util.*;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.yaml.snakeyaml.reader.UnicodeReader;

import com.szyjjk.constants.SzyjjkConstant;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.swing.ImageIcon;

/**
 * 功能描述： 操作文件工具类
 */
public class FileUtil {

	/**
	 * 返回当前文件内容最后一行元素
	 * 
	 * @return [0]最后一行数据 [1]最后一样行数
	 */
	public static String[] getFileContent(String filePath) {
		String[] res = new String[] { null, "0" };
		String content = null;
		BufferedReader reader = null;
		try {
			FileInputStream fileInputStream = new FileInputStream(new File(filePath));
			UnicodeReader unicodeReader = new UnicodeReader(fileInputStream);
			reader = new BufferedReader(unicodeReader);
			String tempString = null;
			int line = 1;
			while ((tempString = reader.readLine()) != null) {
				//System.out.println("line " + line + ": " + tempString.trim());
				line++;
				content = tempString.trim();
			}
			res[0] = content;
			res[1] = line + "";
			reader.close();
		} catch (IOException e) {
			//e.printStackTrace();
			System.out.println(e.getMessage());
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {

				}
			}
		}
		return res;
	}

	/**
	 * 返回列集合
	 * @param filePath
	 * @param spl 截取标记
	 * @param column 第几列
	 * @param row 开始行
	 * @return
	 */
	public static List<String> getFileContent1(String filePath,String spl, int column,int row) {

		List<String> list = new ArrayList<String>();
		String content = null;
		BufferedReader reader = null;
		try {
			FileInputStream fileInputStream = new FileInputStream(new File(filePath));
			UnicodeReader unicodeReader = new UnicodeReader(fileInputStream);
			reader = new BufferedReader(unicodeReader);
			String tempString = null;
			int line = 1;
			while ((tempString = reader.readLine()) != null) {
				// System.out.println("line " + line + ": " + tempString.trim());
				line++;
				if(line<=row) {
					continue;
				}
				content = tempString.trim();
				String[] split = content.split(spl);
				int i = 1;
				for (String string : split) {
					if (StringUtils.isNotBlank(string)) {
						// 第七个元素
						if (i == column) {
							list.add(string);
							break;
						}
						i++;
					}
				}

			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {

				}
			}
		}

		return list;
	}
	/**
	 * output提取数据专用方法
	 * 读取output返回  rch  1 2 3 4 mon  30平均 的   FLOW_OUTcms 这个字段
	 * file.cio 文件 fig.gig  nbyr 前改1
	 * @param filePath
	 * @param spl
	 * @param column
	 * @param row
	 * @return
	 */
	public static Map<String,List<String>> getFileContent2(String filePath) {
		
		Map<String,List<String>> map = new HashMap<>();
		
		String content = null;
		BufferedReader reader = null;
		try {
			FileInputStream fileInputStream = new FileInputStream(new File(filePath));
			UnicodeReader unicodeReader = new UnicodeReader(fileInputStream);
			reader = new BufferedReader(unicodeReader);
			String tempString = null;
			int line = 1;
			while ((tempString = reader.readLine()) != null) {
				// System.out.println("line " + line + ": " + tempString.trim());
				line++;
				//第十行数据
				if(line<=10) {
					continue;
				}
				content = tempString.trim();
				String[] split = content.split(" ");
				List<String> list1  = new ArrayList<String>();
				for (String string : split) {
					if (StringUtils.isNotBlank(string)) {
						list1.add(string);
					}
				}
				if(SzyjjkConstant.RCH35.equals(list1.get(1))||SzyjjkConstant.RCH43.equals(list1.get(1))||
						SzyjjkConstant.RCH49.equals(list1.get(1))||SzyjjkConstant.RCH59.equals(list1.get(1))) {
				//	System.err.println("line " + line + ": " + tempString.trim());
					
						
						//4个河流 12月数据
						List<String> list = map.get(list1.get(1));
						if(CollectionUtils.isEmpty(list)) {
							List<String> mapList = new ArrayList<String>();
							mapList.add(list1.get(6));
							map.put(list1.get(1), mapList);
						}else {
							list.add(list1.get(6));
							map.put(list1.get(1), list);
						}
					
				}
			}
			reader.close();
		} catch (IOException e) {
			//System.out.println(e.getMessage());
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
					
				}
			}
		}
		
		return map;
	}
	/**
	 * output提取数据专用方法
	 * 读取output返回  rch  x 河 的12 月 (每月1号) 氮磷的数据
	 * file.cio 文件 fig.gig  nbyr 前改1
	 * @param filePath 输入文件位置
	 * @return
	 */
	public static Map<String,List<List<String>>> getFileContent4(String filePath,List<String> monthOfDay) {
		
		Map<String,List<List<String>>> map = new HashMap<>();
		
		String content = null;
		BufferedReader reader = null;
		try {
			FileInputStream fileInputStream = new FileInputStream(new File(filePath));
			UnicodeReader unicodeReader = new UnicodeReader(fileInputStream);
			reader = new BufferedReader(unicodeReader);
			String tempString = null;
			int line = 1;
			while ((tempString = reader.readLine()) != null) {
				// System.out.println("line " + line + ": " + tempString.trim());
				line++;
				//第十行数据
				if(line<=10) {
					continue;
				}
				content = tempString.trim();
				String[] split = content.split(" ");
				//行list
				List<String> list1  = new ArrayList<String>();
				for (String string : split) {
					if (StringUtils.isNotBlank(string)) {
						list1.add(string);
					}
				}
				if(SzyjjkConstant.RCH35.equals(list1.get(1))||SzyjjkConstant.RCH43.equals(list1.get(1))||
						SzyjjkConstant.RCH49.equals(list1.get(1))||SzyjjkConstant.RCH59.equals(list1.get(1))) {
					//	System.err.println("line " + line + ": " + tempString.trim());
					if(monthOfDay.contains(list1.get(3))) {
						//4个河流 12月数据
						List<List<String>> list = map.get(list1.get(1));
						
						if(CollectionUtils.isEmpty(list)) {
							List<List<String>> newList = new ArrayList<List<String>>();
							newList.add(list1);
							map.put(list1.get(1), newList);
						}else {
							list.add(list1);
							map.put(list1.get(1), list);
						}
					}
				}
			}
			reader.close();
		} catch (IOException e) {
			//System.out.println(e.getMessage());
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
					
				}
			}
		}
		
		return map;
	}
	/**
	 * 读取指定行范围的数据
	 * @param filePath
	 * @param row
	 * @param row
	 * @return
	 */
	public static Map<Integer,String> getFileContent3(String filePath, int row1,int row2) {
		Map<Integer,String> map = new  TreeMap<>();
		String content = null;
		BufferedReader reader = null;
		try {
			//FileInputStream fileInputStream = new FileInputStream(new File(filePath));
			//UnicodeReader unicodeReader = new UnicodeReader(fileInputStream);
			//reader = new BufferedReader(in);
			reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath),"gbk"));
			
			String tempString = null;
			int line = 0;
			while ((tempString = reader.readLine()) != null) {
				line++;
				if(line>=row1 && line<=row2) {
					//System.out.println("line " + line + ": " + tempString.trim());
					content = tempString.trim();
					map.put(line, content);
				}
				
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
			
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {

				}
			}
		}
		return map;
	}
	/**
	 * 一行一行读取    
	 * @param filePath
	 * @param row1 开始行1
	 * @return
	 */
	public static String getFileContent5(String filePath, int row1) {
		String content = "";
		BufferedReader reader = null;
		try {
			//FileInputStream fileInputStream = new FileInputStream(new File(filePath));
			//UnicodeReader unicodeReader = new UnicodeReader(fileInputStream);
			//reader = new BufferedReader(in);
			reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath),"gbk"));
			
			String tempString = null;
			int line = 0;
			while ((tempString = reader.readLine()) != null) {
				line++;
				if(line==row1) {
					//System.out.println("line " + line + ": " + tempString.trim());
					content = tempString;
					break;
				}
				
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
			
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
					
				}
			}
		}
		return content;
	}
	/**
	 * 一次读取所有数据并返回
	 * @param filePath
	 * @param row1
	 * @return
	 */
	public static String getFileContent6(String filePath) {
		StringBuilder sb = new StringBuilder();
		BufferedReader reader = null;
		try {
			FileInputStream fileInputStream = new FileInputStream(new File(filePath));
			UnicodeReader unicodeReader = new UnicodeReader(fileInputStream);
			reader = new BufferedReader(unicodeReader);
			String tempString = null;
			int line = 1;
			while ((tempString = reader.readLine()) != null) {
				//System.out.println("line " + line + ": " + tempString.trim());
				line++;
				sb.append(tempString.trim());
			}
			
			reader.close();
		} catch (IOException e) {
			//System.out.println(e.getMessage());
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {

				}
			}
		}
		return sb.toString();
	}
	/**
	 * 创建文件并写入内容 path 要创建的文件 content 写入的内容
	 */
	public static void createFileOrWrite(String path, String content) {
		File fff = new File(path);
		if (!fff.exists()) {
			try {
				fff.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {
			FileWriter fileWriter = new FileWriter(path);
			fileWriter.write(content);
			fileWriter.flush();
			fileWriter.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 追加文本内容
	 * 
	 */
	public static void appendContent(String path, String content) {
		FileWriter fw = null;
		try {
			// 如果文件存在，则追加内容；如果文件不存在，则创建文件
			File f = new File(path);
			fw = new FileWriter(f, true);
		} catch (IOException e) {
			e.printStackTrace();
		}
		PrintWriter pw = new PrintWriter(fw);
//		pw.println("Station  hop0pcp,hop1pcp,hop3pcp,");
//		pw.println("Lati    33.2 32.9 32.8");
//		pw.println("Long   -95.6-95.7-95.9");
//		pw.println("Long   -95.6-95.7-95.9");
//		pw.println("Elev     150  151  133");
		pw.println(content);
		pw.flush();
		try {
			fw.flush();
			pw.close();
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 复制一个N个文件到文件下
	 * 
	 * @param oldPath
	 * @param newPath
	 */
	public static void copyFile(String oldPath, String newPath) {
		try {
			(new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹
			File a = new File(oldPath);
			String[] file = a.list();
			File temp = null;
			for (int i = 0; i < file.length; i++) {

				if (!file[i].equals("output.rch") && !(file[i].startsWith("trih-") && file[i].endsWith(".dat"))
						&& !(file[i].startsWith("trim-") && file[i].endsWith(".dat"))) {
					continue;
				}

				if (oldPath.endsWith(File.separator)) {
					temp = new File(oldPath + file[i]);
				} else {
					temp = new File(oldPath + File.separator + file[i]);
				}

				if (temp.isFile()) {
					FileInputStream input = new FileInputStream(temp);
					FileOutputStream output = new FileOutputStream(
							newPath + "/" + DateUtil.getDate() + "_" + (temp.getName()).toString());
					byte[] b = new byte[1024 * 5];
					int len;
					while ((len = input.read(b)) != -1) {
						output.write(b, 0, len);
					}
					output.flush();
					output.close();
					input.close();
				}

			}
		} catch (Exception e) {
			//System.out.println("复制文件内容操作出错");
			e.printStackTrace();
		}
	}

	/**
	 * 复制指定文件到文件下并在文件名前加上时间
	 * 
	 * @param oldPath
	 * @param newPath
	 * @param qianZhui前缀
	 */
	public static void copyFile1(String oldPath, String newPath,String qianZhui) {
		try {
			(new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹
			
			File temp = new File(oldPath); 
			if(temp.exists()) {
				if (temp.isFile()) {
					FileInputStream input = new FileInputStream(temp);
					FileOutputStream output = new FileOutputStream(
							newPath + "/" +qianZhui + (temp.getName()).toString());
					byte[] b = new byte[1024 * 5];
					int len;
					while ((len = input.read(b)) != -1) {
						output.write(b, 0, len);
					}
					output.flush();
					output.close();
					input.close();
				}
			}
		} catch (Exception e) {
			//System.out.println("复制文件内容操作出错");
			e.printStackTrace();
		}
	}
	/**
	 * 复制指定文件到文件下并重命名
	 * 
	 * @param oldPath
	 * @param newPath
	 * @param 重命名
	 */
	public static void copyFile3(String oldPath, String newPath,String newName) {
		try {
			(new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹
			
			File temp = new File(oldPath); 
			if(temp.exists()) {
				if (temp.isFile()) {
					FileInputStream input = new FileInputStream(temp);
					FileOutputStream output = new FileOutputStream(
							newPath + "/" +newName);
					byte[] b = new byte[1024 * 5];
					int len;
					while ((len = input.read(b)) != -1) {
						output.write(b, 0, len);
					}
					output.flush();
					output.close();
					input.close();
				}
			}
		} catch (Exception e) {
			//System.out.println("复制文件内容操作出错");
			e.printStackTrace();
		}
	}
	public static String getPrintSize(long size) {
		//如果字节数少于1024，则直接以B为单位，否则先除于1024，后3位因太少无意义
		if (size < 1024) {
			return String.valueOf(size) + "B";
		} else {
			size = size / 1024;
		}
		//如果原字节数除于1024之后，少于1024，则可以直接以KB作为单位
		//因为还没有到达要使用另一个单位的时候
		//接下去以此类推
		if (size < 1024) {
			return String.valueOf(size) + "KB";
		} else {
			size = size / 1024;
		}
		if (size < 1024) {
			//因为如果以MB为单位的话，要保留最后1位小数，
			//因此，把此数乘以100之后再取余
			size = size * 100;
			return String.valueOf((size / 100)) + "."
					+ String.valueOf((size % 100)) + "MB";
		} else {
			//否则如果要以GB为单位的，先除于1024再作同样的处理
			size = size * 100 / 1024;
			return String.valueOf((size / 100)) + "."
					+ String.valueOf((size % 100)) + "GB";
		}
	}

	/**
	 * 复制指定文件到文件下
	 * 
	 * @param oldPath
	 * @param newPath
	 */
	public static void copyFile2(String oldPath, String newPath) {
		try {
			(new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹
			
			File temp = new File(oldPath); 
			if(temp.exists()) {
				if (temp.isFile()) {
					FileInputStream input = new FileInputStream(temp);
					FileOutputStream output = new FileOutputStream(
							newPath + "/" + (temp.getName()).toString());
					byte[] b = new byte[1024 * 5];
					int len;
					while ((len = input.read(b)) != -1) {
						output.write(b, 0, len);
					}
					output.flush();
					output.close();
					input.close();
				}
			}
		} catch (Exception e) {
			//System.out.println("复制文件内容操作出错");
			e.printStackTrace();
		}
	}
	/**
	 * 复制文件夹下com开头的文件到另一个文件
	 * 
	 * @param oldPath
	 * @param newPath
	 */
	public static void copyFileComStart(String oldPath, String newPath) {
		try {
			(new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹
			File a = new File(oldPath);
			String[] file = a.list();
			File temp = null;
			for (int i = 0; i < file.length; i++) {

				if (!(file[i].startsWith("com"))) {
					continue;
				}

				if (oldPath.endsWith(File.separator)) {
					temp = new File(oldPath + file[i]);
				} else {
					temp = new File(oldPath + File.separator + file[i]);
				}

				if (temp.isFile()) {
					FileInputStream input = new FileInputStream(temp);
					FileOutputStream output = new FileOutputStream(
							newPath + "/" +  (temp.getName()).toString());
					byte[] b = new byte[1024 * 5];
					int len;
					while ((len = input.read(b)) != -1) {
						output.write(b, 0, len);
					}
					output.flush();
					output.close();
					input.close();
				}

			}
		} catch (Exception e) {
			//System.out.println("复制文件内容操作出错");
			e.printStackTrace();
		}
	}
	/**
	 * 上传文件
	 * 
	 * @param files
	 * @param path
	 * @throws Exception
	 */
	public static String fileUpload(MultipartFile mf, String path) throws Exception {

		BufferedOutputStream bos = null;
		BufferedInputStream bis = null;

		// 判断存储的文件夹是否存在
		File file = new File(path);
		if (!file.exists()) {
			file.mkdirs();
		}

		if (!mf.isEmpty()) {
			String originalFilename = mf.getOriginalFilename();

			String fileName = originalFilename.substring(originalFilename.lastIndexOf("/") + 1);

			// 读取文件
			bis = new BufferedInputStream(mf.getInputStream());
			// 指定存储的路径
			String finalpath = path + fileName;
			bos = new BufferedOutputStream(new FileOutputStream(finalpath));
			int len = 0;
			byte[] buffer = new byte[10240];
			while ((len = bis.read(buffer)) != -1) {
				bos.write(buffer, 0, len);
			}
			// 刷新此缓冲的输出流，保证数据全部都能写出
			bos.flush();
			return finalpath;
		}

		if (bis != null) {
			bis.close();
		}
		if (bos != null) {
			bos.close();
		}
return "";
	}
	/**
	 * 删除文件
	 * @param path

	 */
	public static void delFile(String path) {
		File f = new File(path);
		if(f.exists()) {
			f.delete();
		}
	}

    /**
     * 递归删除文件及文件夹
     *
     * @param path
     */
    public static void deleteFiles(String path) {
        File file = new File(path);
        if (file.exists()) {
            if (file.isDirectory()) {//如果是文件夹
                File[] fileList = file.listFiles();//获取文件夹中所有子级文件/夹
                for (File file2 : fileList) {
                    if (file2.isDirectory()) {
                        deleteFiles(file2.getPath());
                    } else {
                        file2.delete();
                    }
                }
            }
        }
        file.delete();
    }

	/**
	 * @Author yangyue
	 * @Description //TODO 下载文件
	 * @Date 9:52 2019/10/28
	 * @Param [request, response, name]
	 * @return void
	 **/
	public static HttpServletResponse  downloadFiles(HttpServletResponse response, String path, String name) {
		String decode = URLDecoder.decode(path+name);
		// 读到流中
		InputStream inStream = null;
		try {
			inStream = new FileInputStream(decode);// 文件的存放路径
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 设置输出的格式
		response.reset();
		response.setContentType("application/octet-stream");
		response.addHeader("Content-Disposition", "attachment; filename=\"" + name + "\"");
		// 循环取出流中的数据
		byte[] b = new byte[1024];
		int len;
		try {
			while ((len = inStream.read(b)) > 0)
				response.getOutputStream().write(b, 0, len);
			inStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return response;
	}

	/**
	 * @Author yangyue
	 * @Description //TODO 汉字转拼音
	 * @Date 17:58 2020/10/19
	 * @Param [chinese]
	 * @return java.lang.String
	 **/
	public static String ToPinyin(String chinese){
		String pinyinStr = "";
		char[] newChar = chinese.toCharArray();
		HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
		defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		for (int i = 0; i < newChar.length; i++) {
			if (newChar[i] > 128) {
				try {
					pinyinStr += PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat)[0];
				} catch (BadHanyuPinyinOutputFormatCombination e) {
					e.printStackTrace();
				}
			}else{
				pinyinStr += newChar[i];
			}
		}
		return pinyinStr;
	}
	
	 public static boolean jpgZhuanPng(String imgSrc, String imgTarget) {
	        File file = new File(imgSrc);
	        if(!file.exists()) {
	        	return false;
	        }
	        InputStream is = null;
	        boolean result = false;
	        try {
	            is = new FileInputStream(file);
	            // 如果是MultipartFile类型，那么自身也有转换成流的方法：is = file.getInputStream();
	            BufferedImage bi = ImageIO.read(is);
	            Image image = (Image) bi;
	            ImageIcon imageIcon = new ImageIcon(image);
	            BufferedImage bufferedImage = new BufferedImage(imageIcon.getIconWidth(), imageIcon.getIconHeight(),
	                    BufferedImage.TYPE_4BYTE_ABGR);
	            Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics();
	            g2D.drawImage(imageIcon.getImage(), 0, 0, imageIcon.getImageObserver());
	            int alpha = 0;
	            for (int j1 = bufferedImage.getMinY(); j1 < bufferedImage.getHeight(); j1++) {
	                for (int j2 = bufferedImage.getMinX(); j2 < bufferedImage.getWidth(); j2++) {
	                    int rgb = bufferedImage.getRGB(j2, j1);
	                    int R = (rgb & 0xff0000) >> 16;
	                    int G = (rgb & 0xff00) >> 8;
	                    int B = (rgb & 0xff);
	                    if (((255 - R) < 30) && ((255 - G) < 30) && ((255 - B) < 30)) {
	                        rgb = ((alpha + 1) << 24) | (rgb & 0x00ffffff);
	                    }
	                    bufferedImage.setRGB(j2, j1, rgb);
	                }
	            }
	            g2D.drawImage(bufferedImage, 0, 0, imageIcon.getImageObserver());
	            result = ImageIO.write(bufferedImage, "png", new File(imgTarget));// 直接输出文件
	        } catch (Exception e) {
	            e.printStackTrace();
	            result = false;
	        } finally {
	            if (is != null) {
	                try {
	                    is.close();
	                } catch (IOException e) {
	                   e.printStackTrace();
	                }
	            }
	        }
	        return result;
	    }


}
